package com.example.home.ui

import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.launcher.ARouter
import com.example.common.ARouterPath
import com.example.home.adapter.HomePageAdapter
import com.example.home.databinding.FragmentHomeBinding
import com.example.home.intent.VideoIntent
import com.example.home.state.VideoState
import com.example.home.viewmodel.VideoViewModel
import com.example.mvi_core.model.ui.BaseFragment
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayout.OnTabSelectedListener
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch


class HomeFragment : BaseFragment() {
    lateinit var binding: FragmentHomeBinding
   private  val videoViewModel by lazy { VideoViewModel() }
    lateinit var  adapter:HomePageAdapter
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding=FragmentHomeBinding.inflate(inflater,container,false)
        return binding.root
    }

    override fun initData() {
        super.initData()
        lifecycleScope.launchWhenCreated{
            videoViewModel.channel.send(VideoIntent.GetVideoType)
        }
        lifecycleScope.launch{
            videoViewModel.observeState.collect {
                when(it){
                    is VideoState.Loading->{
                        Toast.makeText(requireContext(), "加载中", Toast.LENGTH_SHORT).show()
                    }
                    is VideoState.Success->{
                     adapter=HomePageAdapter(it.list,childFragmentManager)
                        binding.homeVp.adapter=adapter
                        binding.homeTab.setupWithViewPager(binding.homeVp)
                        binding.homeVp.adapter?.notifyDataSetChanged()
                    }
                    is VideoState.Failure->{
                        Toast.makeText(requireContext(), it.msg, Toast.LENGTH_SHORT).show()
                    }
                    else->{
                        Toast.makeText(requireContext(), "其他", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }


    }




}